package com.example.wanxiang.service.Impl;

import com.example.wanxiang.dto.UserRequest;
import com.example.wanxiang.entity.User;
import com.example.wanxiang.repository.UserRepository;
import com.example.wanxiang.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class UserImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    public User deleteUser(Long id) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User updateUser(UserRequest userRequest) {
        User byEmail = userRepository.findByEmail(userRequest.getEmail());

        //若密码相同就可以更改个人数据
        if (userRequest.getPassword().equals(byEmail.getPassword())) {
            byEmail.setPassword(passwordEncoder.encode(userRequest.getPasswordAfterChange()));
            byEmail.setEmail(userRequest.getEmail());
            byEmail.setUsername(userRequest.getUsername());
        }
        return userRepository.save(byEmail);
    }

    @Override
    public User updateUserLogin(User userRequest) {
        User byEmail = userRepository.findByEmail(userRequest.getEmail());
        if (userRequest.getPassword().equals(byEmail.getPassword())) {
            byEmail.setLoginTime(LocalDateTime.now());
        }
        return userRepository.save(byEmail);
    }


}
